package midway.madness.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import midway.madness.R;
import midway.madness.post.PostObject;
import midway.madness.post.article.ArticleObject;
import midway.madness.post.image.PictureObject;
import midway.madness.post.podcast.PodcastObject;
import midway.madness.post.video.VideoObject;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Application;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class ApplicationEx extends Application {

	public static final int HANDLE_ERR = 0;
	private DefaultHttpClient client = null;
	
	public void onCreate(){
		super.onCreate();
		client = createHttpClient();
	}
	
	public void onLowMemory(){
		super.onLowMemory();
		shutdownHttpClient();
	}
	
	public void onTerminate(){
		super.onTerminate();
		shutdownHttpClient();
	}
	
	public boolean isConnected(){
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = cm.getActiveNetworkInfo();
		return (null != info && info.isConnectedOrConnecting());
	}
	
	public JSONObject getJson(String url) throws JSONException{
		if (!isConnected()){
			JSONObject obj = new JSONObject();
			obj.put("status", "network");
			return obj;
		}
		StringBuilder sb = new StringBuilder();
		HttpGet get = new HttpGet(url);
		JSONObject obj = null;
		try{
			HttpResponse response = client.execute(get);
			if (response.getStatusLine().getStatusCode() == 200){
				BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
				String line;
				while ((line = reader.readLine()) != null){
					sb.append(line);
				}
				reader.close();
				obj = new JSONObject(sb.toString());
			}else{
				obj = new JSONObject();
				obj.put("status", "unknown");
			}
		}catch (UnknownHostException uhe){
			obj = new JSONObject();
			obj.put("status", "network");
		} catch (ClientProtocolException e) {
			obj = new JSONObject();
			obj.put("status", "network");
		} catch (IOException e) {
			obj = new JSONObject();
			obj.put("status", "reader");
		}
		return obj;
	}
	
	public JSONObject postJson(String baseUrl, String[] tags, String[] vals) throws JSONException{
		if (!isConnected()){
			JSONObject obj = new JSONObject();
			obj.put("status", "network");
			return obj;
		}
		StringBuilder sb = new StringBuilder();
		HttpPost post = new HttpPost(baseUrl);
		JSONObject obj = null;
		try{
			List<KVP> kvp = new ArrayList<KVP>();
			for (int i = 0; i < tags.length; i++){
				kvp.add(new KVP(tags[i], vals[i]));
			}
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(kvp);
			post.setEntity(entity);
			HttpResponse response = client.execute(post);
			if (null != response){
				InputStreamReader reader = new InputStreamReader(response
						.getEntity().getContent());
				sb = new StringBuilder();
				int count = 0;
				char[] text = new char[1024];
				while ((count = reader.read(text, 0, 1024)) != -1) {
					sb.append(text, 0, count);
				}
				obj = new JSONObject(sb.toString());
			}else{
				obj = new JSONObject();
				obj.put("status", "null");
			}
		}catch (UnknownHostException uhe){
			obj = new JSONObject();
			obj.put("status", "network");
		} catch (ClientProtocolException e) {
			obj = new JSONObject();
			obj.put("status", "network");
		} catch (IOException e) {
			obj = new JSONObject();
			obj.put("status", "reader");
		}
		return obj;
	}
	
	public Bitmap loadBitmap(String url) throws IOException {
		Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(url).getContent());
	    return bitmap;
	}

	public String parseForUrl(String url) {
		String retVal = null;
		
		int index = url.indexOf("href=");
		if (index < 0){
			return retVal;
		}
		retVal = url.substring(index+6);
		retVal = retVal.substring(0, retVal.indexOf("\""));
		
		return retVal;
	}

	public PostObject whatAmI(JSONObject post) throws JSONException, IOException{
		PostObject retVal = null;
		String title = post.getString("title");
		String author = post.getJSONObject("author").getString("name");
		String date = post.getString("date");
		String slug = post.getString("slug");
		String content = post.getString("content");
		JSONArray comArr = post.getJSONArray("comments");
		String[] comments = new String[post.getInt("comment_count")];
		for (int j = 0; j < comArr.length(); j++){
			JSONObject temp = (JSONObject) comArr.get(j);
			comments[j] = temp.getString("name") + "->" + temp.getString("date") + "->" + temp.getString("content");
		}
		int id = post.getInt("id");
		JSONArray arr = post.getJSONArray("categories");
		for (int i = 0; i < arr.length(); i++){
			JSONObject obj = arr.getJSONObject(i);
			int typeId = obj.getInt("id");
			if (typeId == 4){ //PODCAST
				retVal = new PodcastObject(getBaseContext(), id, author, title, parseForUrl(content), date, slug, comments); 
			}else if(typeId == 135){//PIC
				retVal = new PictureObject(getBaseContext(), id, author, title, parseForUrl(content), date, slug, comments, null, post.getJSONArray("attachments").toString());
			}else if (typeId == 41){//VIDEO
				retVal = new VideoObject(getBaseContext(), id, author, title, parseForUrl(content), date, slug, comments);
			}
		}
		if (null == retVal){
			//If it isn't a pic, vid, or podcast, its an article
			String start = post.getString("excerpt");
			start = start.substring(0, 15);
			int index = content.indexOf(start);
			if (index < 0){
				return null;
			}
			content = content.substring(index);
			retVal = new ArticleObject(getBaseContext(), id, author, title, content, date, slug, comments);
		}
		return retVal;
	}
	
	public AlertDialog handleError(Context context, String problem){
		return getErrorDialog(context, getMessage(problem));
	}
	
	public String getMessage(String problem){
		if (problem.equals("network")){
			return getBaseContext().getResources().getString(R.string.network_error);
		}else if (problem.equals("reader")){
			return getBaseContext().getResources().getString(R.string.reader_error);
		}else if (problem.equals("post")){
			return getBaseContext().getResources().getString(R.string.post_error);
		}else if (problem.equals("bitmap")){
			return getBaseContext().getResources().getString(R.string.bitmap_error);
		}
		return getBaseContext().getResources().getString(R.string.unknown_error);
	}

	private AlertDialog getErrorDialog(Context context, String message) {
		Builder builder = new Builder(context);
		builder.setMessage(message);
		builder.setNeutralButton("Okay", null);
		return builder.create();
	}
	
	public DefaultHttpClient getHttpClient(){
		if (null == client){
			client = new DefaultHttpClient();
		}
		return client;
	}
	
	private DefaultHttpClient createHttpClient(){
		return new DefaultHttpClient();
	}
	
	private void shutdownHttpClient(){
		if (null != client && null != client.getConnectionManager()){
			client.getConnectionManager().shutdown();
		}
	}
	
}
